package com.lxh.student.filter;

import com.lxh.student.entity.TeacherDetails;
import com.lxh.student.utils.JwtUtil;
import com.lxh.student.utils.RedisCache;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lxh
 * @date 2023/4/7 20:29
 * OncePerRequestFilter 只走一次，请求前
 */

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1.获取token
        String jwt = request.getHeader("jwt");
        if(ObjectUtils.isEmpty(jwt)){
            log.info("没有jwt！");
            //放行，让后面的过滤器来处理
            filterChain.doFilter(request,response);
            return;
        }
        //2.解析token
        try {
            log.info("有jwt");
            Claims claims = JwtUtil.parseJWT(jwt);
            log.info("jwt合法");
            //3.获取userId,从redis中获取用户信息
            String teacherId = claims.getSubject();
            log.info(teacherId);
            try {
                TeacherDetails teacherDetails = redisCache.getCacheObject("teacher:login:" + teacherId,TeacherDetails.class);
                log.info(teacherDetails.getTeacher().getName());
                if (ObjectUtils.isEmpty(teacherDetails)){
                    throw new RuntimeException("jwt合法，但redis id没有对应用户信息！");
                }
                //4.封装Authentication
                log.info("封装Authentication");
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                        = new UsernamePasswordAuthenticationToken(teacherDetails, null, teacherDetails.getAuthorities());
                //5.存入SecurityContextHolder
                log.info("封装后存入SecurityContextHolder");
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }catch (Exception e){
                e.printStackTrace();
            }
        } catch (Exception e) {
            throw new RuntimeException("jwt不合法！");
        }
        filterChain.doFilter(request,response);
    }
}
